﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace XBLIGUK2011Talk2
{
    public class SkyBox : DrawableGameComponent
    {
        private Model skyboxMesh;
        public Quaternion Rotation;
        public Vector3 Scale;
        Effect effect;

        public Base3DCamera camera
        {
            get { return (Base3DCamera)Game.Services.GetService(typeof(Base3DCamera)); }
        }


        public string textureAsset;

        public SkyBox(Game game, string textureAsset) : base(game)
        {
            this.textureAsset = textureAsset;

            Rotation = new Quaternion(0, 0, 0, 1);
            Scale = new Vector3(99, 99, 99);
        }

        public override void Draw(GameTime gameTime)
        {
            if (Enabled && Visible)
            {

                Game.GraphicsDevice.BlendState = BlendState.Opaque;

                Matrix World = Matrix.CreateScale(Scale) *
                                Matrix.CreateFromQuaternion(Rotation) *
                                Matrix.CreateTranslation(camera.Position);

                if (effect == null)
                    effect = Game.Content.Load<Effect>("Shaders/SkyBoxShader");

                if (skyboxMesh == null)
                    skyboxMesh = Game.Content.Load<Model>("Models/SkyBox");

                effect.Parameters["World"].SetValue(World);
                effect.Parameters["View"].SetValue(camera.View);
                effect.Parameters["Projection"].SetValue(camera.Projection);
                effect.Parameters["surfaceTexture"].SetValue(Game.Content.Load<TextureCube>(textureAsset));

                effect.Parameters["EyePosition"].SetValue(camera.Position);

                for (int pass = 0; pass < effect.CurrentTechnique.Passes.Count; pass++)
                {
                    for (int msh = 0; msh < skyboxMesh.Meshes.Count; msh++)
                    {
                        ModelMesh mesh = skyboxMesh.Meshes[msh];
                        for (int prt = 0; prt < mesh.MeshParts.Count; prt++)
                            mesh.MeshParts[prt].Effect = effect;
                        mesh.Draw();
                    }
                }

                base.Draw(gameTime);
            }
        }
    }
}
